#include<stdio.h>



struct ListNode {
    int val;
    struct ListNode* next;
};


struct ListNode* detectCycle(struct ListNode* head) {
    struct ListNode* fast, * slow, * copy, * cur;
    fast = slow = cur = head;
    while (fast && fast->next)
    {
        fast = fast->next->next;
        slow = slow->next;
        if (slow = fast)
        {
            copy = fast->next;
            break;
        }
    }
    if (fast == NULL || fast->next == NULL)
    {
        return NULL;
    }
    fast = NULL;
    int k = 0, c = 0;
    while (cur)
    {
        cur = cur->next;
        k++;
    }
    while (copy)
    {
        copy = copy->next;
        c++;
    }
    copy = slow->next;
    cur = head;
    if (k > c)
    {
        int a = k - c;
        while (a--)
        {
            cur = cur->next;
        }
    }
    if (k < c)
    {
        int a = c - k;
        while (a--)
        {
            copy = copy->next;
        }
    }
    while (copy != cur)
    {
        copy = copy->next;
        cur = cur->next;
    }
    fast = slow;
    return cur;
}